package com.novak.rss.reader;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class RSSDBHelper extends SQLiteOpenHelper
{
  private static final String DATABASE_NAME = "RSS_FEEDS";
  private static final int DATABASE_VERSION = 2;
  private static final String RSS_TABLE_NAME = "feeds";
  private static final String RSS_TABLE_CREATE = "CREATE TABLE "
      + RSS_TABLE_NAME + " (name TEXT, url TEXT,count INTEGER);";

  RSSDBHelper(Context context)
  {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }

  @Override
  public void onCreate(SQLiteDatabase db)
  {
    // TODO Auto-generated method stub
   // db.setLocale(Locale.CHINA);
    db.execSQL(RSS_TABLE_CREATE);

  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion,
      int newVersion)
  {
    // TODO Auto-generated method stub

  }

  public List<Feed> getAll() throws SQLException
  {
    List<Feed> feeds = new ArrayList<Feed>();
    SQLiteDatabase db = getReadableDatabase();
    String col[] =
    { "name", "url", "count" };
    Cursor cur = db.query(RSS_TABLE_NAME, col, null, null, null, null,
        null);
    cur.moveToFirst();
    while (!cur.isAfterLast())
    {
      Feed f = new Feed(cur.getString(0), cur.getString(1), cur.getInt(2));
      feeds.add(f);
      cur.moveToNext();
    }
    db.close();
    return feeds;
  }

  public void delete(Feed f) throws SQLException
  {
    SQLiteDatabase db = getWritableDatabase();
    String where = "name='" + f.getName() + "'";
    db.delete(RSS_TABLE_NAME, where, null);
    db.close();
  }

  public void add(Feed f) throws SQLException
  {
    SQLiteDatabase db = getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put("name", f.getName());
    cv.put("url", f.getUrl());
    cv.put("count", f.getCount());
    db.insert(RSS_TABLE_NAME, null, cv);
    db.close();
  }
  public void addCount(Feed f){
    SQLiteDatabase db = getWritableDatabase();
    String where = "name='" + f.getName() + "'";
    ContentValues cv = new ContentValues();
    cv.put("name", f.getName());
    cv.put("url", f.getUrl());
    cv.put("count", f.getCount());
    db.update(RSS_TABLE_NAME, cv, where, null);
  }

}
